package com.sms.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sms.DB.ConnectDB;
import com.sms.DB.OperateDB;
import com.sms.user.User;

public class AddPeopleServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
			response.setContentType("text/html;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			request.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			
			boolean isSuccess = true;
			String msg = "";
			
			String role = request.getParameter("login-id");
			String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "utf-8");
			String no = request.getParameter("number");
			String sex = (request.getParameter("sex").equals("boy"))?"男":"女";
			
			Connection conn = ConnectDB.getConnection();
			boolean autoCommit;
			try {
				autoCommit = conn.getAutoCommit();
				conn.setAutoCommit(false);// 取消自动提交
			
				if(role.equals("teacher")) {//添加的人员是老师
					if(!User.addTeacher(no, name, sex)) {
						isSuccess = false;
					}
				} else {//添加的人员是组长或者成员
					String type = request.getParameter("type");
					String teacher = request.getParameter("header");
					String t[] = teacher.split(",");
					teacher = t[0];
					String major = new String(request.getParameter("major").getBytes("ISO-8859-1"), "utf-8");
					
					if(!User.addStudent(no, name, sex, type, major, teacher)) {
						isSuccess = false;
					} 
				}
				
				if (isSuccess) {
					conn.commit();// 手动提交
					msg = "ok";
				} else {
					conn.rollback();
					msg = "error";
				}
				conn.setAutoCommit(autoCommit);// 恢复现场
			} catch (SQLException e) {
				e.printStackTrace();
				isSuccess = false;
			} finally {
				OperateDB.close(conn);
			}
			
			out.flush();
			out.write(msg);
			out.close();
	}

}
